﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using DefaultScope;
using Microsoft.Synchronization.ClientServices.IsolatedStorage;
using System.Collections.ObjectModel;

namespace Klient.Forms
{
    public partial class MySuppliers : PhoneApplicationPage
    {
        #region Dependency Property
        public static DependencyProperty AllSuppliersProperty = DependencyProperty.Register(
            "AllSuppliers", typeof(ObservableCollection<Pair<bool, Suppliers>>), typeof(MySuppliers), null);
        public ObservableCollection<Pair<bool, Suppliers>> AllSuppliers
        {
            get
            {
                return (ObservableCollection<Pair<bool, Suppliers>>)GetValue(AllSuppliersProperty);
            }
            set
            {
                SetValue(AllSuppliersProperty, value);
            }
        }
        #endregion

        DefaultScopeOfflineContext shippersContext;
        private string employeeID;

        public MySuppliers()
        {
            DataContext = this;

            
            InitializeComponent();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            shippersContext = new DefaultScopeOfflineContext("suppliers", new Uri("http://localhost:4000/DefaultScopeSyncService.svc/"));
            
            if (e.NavigationMode == System.Windows.Navigation.NavigationMode.New)
            {
                if (NavigationContext.QueryString.Values.Count > 1) //czyli dodano suppliera
                {
                    Suppliers supplier = new Suppliers();
                    supplier.SupplierID = shippersContext.SuppliersCollection.Max(s => s.SupplierID) + 1; //wybierz niepowtarzajace sie id
                    supplier.Region = null;
                    supplier.PostalCode = NavigationContext.QueryString["PostalCode"];
                    supplier.Phone = NavigationContext.QueryString["Phone"];
                    supplier.HomePage = null;
                    supplier.Fax = null;
                    supplier.Country = NavigationContext.QueryString["Country"];
                    supplier.ContactTitle = NavigationContext.QueryString["ContactTitle"];
                    supplier.ContactName = NavigationContext.QueryString["ContactName"];
                    supplier.CompanyName = NavigationContext.QueryString["CompanyName"];
                    supplier.City = NavigationContext.QueryString["City"];
                    supplier.Address = NavigationContext.QueryString["Address"];

                    shippersContext.AddSuppliers(supplier);
                    shippersContext.SaveChanges();
                }
            }

            NavigationContext.QueryString.TryGetValue("employeeID", out employeeID);

            shippersContext.CacheController.ControllerBehavior.SerializationFormat = Microsoft.Synchronization.ClientServices.SerializationFormat.ODataAtom;
            shippersContext.CacheController.RefreshCompleted += new EventHandler<Microsoft.Synchronization.ClientServices.RefreshCompletedEventArgs>(CacheController_RefreshCompleted);
            shippersContext.LoadCompleted += new EventHandler<LoadCompletedEventArgs>(context_LoadCompleted);
            
            this.Loaded += new RoutedEventHandler(MySuppliers_Loaded);
        }

        void MySuppliers_Loaded(object sender, RoutedEventArgs e)
        {
            progressBar.Visibility = Visibility.Collapsed;
            shippersContext.LoadAsync();
        }

        void context_LoadCompleted(object sender, LoadCompletedEventArgs e)
        {
            Dispatcher.BeginInvoke(
                delegate
                {
                    AllSuppliers = new ObservableCollection<Pair<bool, Suppliers>>(Pair<bool, Suppliers>.createPair(shippersContext.SuppliersCollection));
                }
                );
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            shippersContext.Close();
        }

        void CacheController_RefreshCompleted(object sender, Microsoft.Synchronization.ClientServices.RefreshCompletedEventArgs e)
        {
            AllSuppliers = new ObservableCollection<Pair<bool, Suppliers>>(Pair<bool, Suppliers>.createPair(shippersContext.SuppliersCollection));
            progressBar.Visibility = Visibility.Collapsed;
            if (e.Error != null)
                Dispatcher.BeginInvoke(delegate { MessageBox.Show(e.Error.ToString()); });
        }

        private void refreshBtn_Click(object sender, RoutedEventArgs e)
        {
            if (!shippersContext.CacheController.IsBusy)
            {
                progressBar.Visibility = Visibility.Visible;
                shippersContext.SaveChanges();
                shippersContext.CacheController.RefreshAsync();
                shippersContext.LoadAsync();
            }
        }

        private void addBtn_Click(object sender, RoutedEventArgs e)
        {
            if (!shippersContext.CacheController.IsBusy)
            {
                NavigationService.Navigate(new Uri("/Forms/NewSupplier.xaml?employeeID=" + employeeID, UriKind.Relative));
            }
        }

        private void deleteBtn_Click(object sender, RoutedEventArgs e)
        {
            if (!shippersContext.CacheController.IsBusy)
            {
                progressBar.Visibility = Visibility.Visible;
                foreach (Object o in suppliers.Items)
                {
                    Pair<bool, Suppliers> p = (Pair<bool, Suppliers>)o;
                    if (p.first == true)
                    {
                        shippersContext.DeleteSuppliers(p.second);
                    }
                }
                try
                {
                    shippersContext.SaveChanges();
                }
                catch (SaveFailedException exc)
                {
                    Console.WriteLine(exc.StackTrace);
                }
                shippersContext.CacheController.RefreshAsync();
                shippersContext.LoadAsync();
                
            }
        }
    }
}